const DISTANCE = 80;
const DURATION = 500;
const animationMap = new WeakMap();

const ob = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (entry.isIntersecting) {
      console.log(entry.target.getAnimations());
      // 也可以，但是如果有自己的动画，就不知道是第几个了
      // entry.target.getAnimations()[0].play()
      const animation = animationMap.get(entry.target);
      animation.play();
      // 只需要播放一次
      ob.unobserve(entry.target);
    }
  }
});

function isBelowViewPort(el) {
  const rect = el.getBoundingClientRect();
  return rect.top > window.innerHeight;
}

export default {
  mounted(el) {
    if (!isBelowViewPort(el)) {
      return;
    }
    // 为了考虑通用性，可以使用animation api，因为改变style的话，可能元素本身就设置了相关的style
    const animation = el.animate(
      [
        {
          transform: `translateY(${DISTANCE}px)`,
          opacity: 0.5,
        },
        {
          transform: `translateY(0px)`,
          opacity: 1,
        },
      ],
      {
        duration: DURATION,
        easing: "ease-in-out",
      }
    );
    animation.pause();
    animationMap.set(el, animation);
    ob.observe(el);
  },
  unmounted(el) {
    ob.unobserve(el);
  },
};
